<template>
  <div class="container">
    <el-card class="box-card" shadow="always">
      <el-row :gutter="24">
        <el-col :span="16">
          <el-form inline @submit.native.prevent="search">
            <el-form-item label="搜索">
              <el-input
                v-model="searchForm.queryConditions"
                clearable
                placeholder=""
                prefix-icon="el-icon-search"
                size="medium"
              />
            </el-form-item>
            <el-form-item label="组织">
              <el-select
                v-model="organizationList.organizeName"
                clearable
                placeholder="全部"
                style="width: 150px"
                @change="organizationSelected"
              >
                <el-option
                  v-for="item in organizationList"
                  :key="item.id"
                  :value="item.id"
                  :label="item.organizeName"
                />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button native-type="submit" size="medium" type="primary"
                >搜索</el-button
              >
            </el-form-item>
          </el-form>
        </el-col>
        <el-col :span="8">
          <el-button icon="el-icon-download" type="primary" class="btn">
            <a download :href="exportUrl"> 导出 </a>
          </el-button>

          <el-button
            class="btn"
            type="primary"
            icon="el-icon-circle-plus-outline"
            @click="addManagerDialog"
            >添加</el-button
          >
          <!-- <el-upload
            class="upload-demo"
            :action="uploadURL"
            :headers="headers"
            :show-file-list="false"
            :on-success="onSuccess"
            :on-error="onError"
          >
            <el-button icon="el-icon-upload2" type="primary"
              >点击上传</el-button
            >
          </el-upload> -->
        </el-col>
      </el-row>
      <div>
        <el-table :data="list" border style="width: 100%" v-loading="purchaserLoading">
          <el-table-column
            type="index"
            width="50"
            label="序号"
            align="center"
          />
          <el-table-column label="头像" width="70" align="center">
            <template slot-scope="scope">
              <el-avatar :src="scope.row.avatar"></el-avatar>
            </template>
          </el-table-column>

          <el-table-column prop="username" label="用户名" align="center" />
          <el-table-column prop="mobilePhone" label="手机号" align="center" />
          <el-table-column label="归属组织" align="center">
            <template slot-scope="scope">
              {{ scope.row.organization.organizeName }}
            </template>
          </el-table-column>
          <el-table-column prop="description" label="业务描述" align="center" />
          <el-table-column label="操作" align="center">
            <template slot-scope="scope">
              <el-tooltip content="查看信息" placement="top">
                <el-button
                  size="mini"
                  icon="el-icon-search"
                  circle
                  @click="showDialog(scope.row)"
                />
              </el-tooltip>
              <el-tooltip content="编辑信息" placement="top">
                <el-button
                  size="mini"
                  type="primary"
                  icon="el-icon-edit"
                  circle
                  @click="editManagerDialog(scope.row)"
                />
              </el-tooltip>
              <el-tooltip content="还原最初密码" placement="top">
                <el-button
                  size="mini"
                  type="warning"
                  icon="el-icon-refresh"
                  circle
                  @click="refreshPassword(scope.row.id)"
                />
              </el-tooltip>
              <el-tooltip content="删除管理员" placement="top">
                <el-button
                  size="mini"
                  el-button
                  type="danger"
                  icon="el-icon-delete"
                  circle
                  @click="deletePurchaserById(scope.row)"
                />
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>

        <el-pagination
          :current-page="paging.current"
          :page-sizes="paging.pageSizes"
          :page-size="paging.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="paging.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>

      <Dialog
        :visible="purchaserInfoVisible"
        :data="purchaserInfo"
        @cancel="cancel"
      />
      <edit-dialog
        :index="index"
        :organization-list="organizationList"
        :title="dialogTitle"
        :visible="editDialogVisible"
        :purchaser-info="purchaserInfo"
        @cancel="cancel"
        @ok="ok"
      />
    </el-card>
  </div>
</template>

<script>
// import { getToken } from "@/utils/auth";
import {
  getAllPurchasersByPageAndConditions,
  deletePurchaser,
  addPurchaser,
  updatePurchaserById,
} from "@/api/purchaser.js";
import { resetPassword } from "@/api/common";
import { getAllOrganizationInfos } from "@/api/organization";
import Dialog from "./components/Dialog";
import EditDialog from "./components/editDialog";

export default {
  name: "PurchaserManage",
  components: { Dialog, EditDialog },
  data() {
    return {
      searchForm: {
        queryConditions: "",
        organizeId: "",
      },
      organizationList: [],
      list: [],
      paging: {
        total: 0,
        current: 1,
        pageSizes: [5, 10, 15],
        size: 5,
      },
      purchaserInfoVisible: false,
      purchaserInfo: {},
      editDialogVisible: false,
      purchaserLoading: false,
      dialogTitle: "",
      index: 0, // 0 添加；1 编辑；2 查看信息
      // headers: {
      //   Authorization: getToken(),
      // },
    };
  },
  computed: {
    exportUrl() {
      return (
        process.env.VUE_APP_BASE_API +
        "/manager/exportManagerExcel/" +
        this.$store.getters.accountId
      );
    },
  },
  created() {
    this.purchaserLoading = true;
    this.getData();
    this.getOrganizations();
    // console.log(getToken())
  },
  methods: {
    async getOrganizations() {
      const result = await getAllOrganizationInfos();
      this.organizationList = result.data;
      // console.log('@@@@',this.organizationList)
    },
    search() {
      this.paging.current = 1;
      this.purchaserLoading = true;
      this.getData();
    },
    getData() {
      const form = {
        ...this.searchForm,
        managerId: this.$store.getters.accountId,
        page: this.paging.current,
        pageSize: this.paging.size,
      };
      getAllPurchasersByPageAndConditions(form)
        .then(({ data }) => {
          console.log(data);
          this.list = data.purchaserInfos;
          //this.paging.size = data.size
          this.paging.total = data.totalCount;
          this.purchaserLoading = false;
        })
        .catch((err) => {
          // 如果没有数据就显示为空
          this.list = [];
          // 返还每页显示的条数
          //this.paging.size = res.data.size;
          this.paging.total = 0;
          this.purchaserLoading = false;
        });
    },
    handleSizeChange(val) {
      this.paging.current = 1;
      this.paging.size = val;
      this.getData();
    },
    handleCurrentChange(val) {
      this.paging.current = val;
      this.getData();
    },
    showDialog(row) {
      this.purchaserInfoVisible = true;
      this.purchaserInfo = row;
      this.index = 2;
    },
    refreshPassword(accountId) {
      console.log(accountId);
      this.$confirm("将还原该账号密码,此操作不可逆 是否确定?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const result = await resetPassword({ accountId: accountId });
          console.log(result);
          if (result.code === 200) {
            this.$message({
              type: "success",
              message: "还原成功!",
            });
            this.getData();
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "操作取消",
          });
        });
    },
    deletePurchaserById(row) {
      this.$confirm("此操作将永久删除这条数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const result = await deletePurchaser({ purchaserId: row.id, managerId: this.$store.getters.accountId });
          console.log(result);
          if (result.code === 200) {
            this.$message({
              type: "success",
              message: "删除成功!",
            });
            this.getData();
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    organizationSelected(val) {
      this.searchForm.organizeId = val;
      this.search();
    },
    editManagerDialog(row) {
      this.dialogTitle = "编辑管理员信息";
      this.editDialogVisible = true;
      this.purchaserInfo = this.extendCopy(row);
      this.index = 1;
    },
    // 对象的深拷贝
    // 对象进行深拷贝，否则“编辑”框内修改内容也会影响到页面
    extendCopy(p) {
      var c = {};
      for (var i in p) {
        c[i] = p[i];
      }
      return c;
    },
    addManagerDialog() {
      this.dialogTitle = "添加管理员";
      this.editDialogVisible = true;
      this.index = 0;
    },
    cancel() {
      if (this.index === 2) {
        this.purchaserInfoVisible = false;
      } else {
        this.editDialogVisible = false;
      }
      this.index = 0;
    },
    editpurchaserInfo(data) {
      // eslint-disable-next-line no-async-promise-executor
      return new Promise(async (resolve, reject) => {
        if (this.index) {
          // 编辑导师信息
          // console.log(val)
          const result = await updatePurchaserById(data);
          // console.log(res)
          if (result.code === 200) {
            this.$message.success("修改成功");
            resolve(result);
          } else {
            this.$message.error("修改失败，请重试");
            reject(result);
          }
        } else {
          const result = await addPurchaser(data);
          // console.log(res)
          if (result.code === 200) {
            this.$message.success("新增成功");
            resolve(result);
          } else {
            this.$message.error("新增失败，请重试");
            reject(result);
          }
        }
      });
    },
    async ok(val) {
      const response = await this.editpurchaserInfo(val);
      console.log(response);
      if (response.code === 200) {
        this.editDialogVisible = false;
        this.getData();
        this.index = 0;
      }
    },
    // onSuccess(response, file, fileList) {
    //   console.log(response);
    //   if (response.code !== 200) {
    //     this.$message.error("上传失败，请重试");
    //   } else {
    //     this.$message.success("上传成功");
    //     this.getData();
    //   }
    // },
    // onError(error, file, fileList) {
    //   console.log(error);
    // },
  },
};
</script>
<style lang="scss" scoped>
.el-pagination {
  margin-top: 20px;
  text-align: right;
}
.btn {
  float: right;
  margin-left: 20px;
}
</style>
